package com.app.piemoment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.LayoutParams;

import com.app.piemoment.api.ApiResult;
import com.app.piemoment.api.ApiReturnResultListener;
import com.app.piemoment.api.TestApi;
import com.app.piemoment.config.Config;
import com.app.piemoment.entity.Subject;
import com.app.piemoment.util.ToastManager;
import com.app.piemoment.util.Utils;

public class TesttingActivity extends BaseActivity {

	private ImageView headicon;
	private TextView current_qus;
	private TextView question_text;
	private Button btn_next;
	protected ArrayList<Subject> list;
	private int position = 0;
	private LinearLayout radioGroup;
	private String module;

	public TesttingActivity() {
		mainViewId = R.layout.testing;
	}

	@Override
	protected void initMainView() {
		module = getIntent().getStringExtra("module");
		String title = null;
		if(Config.Modoule_Lift.equals(module)) {
			title = "人生观";
		}else if(Config.Modoule_Personality.equals(module)) {
			title = "价值观";
		}else if(Config.Modoule_Love.equals(module)) {
			title = "爱情观";
		}else  {
			title = "交往模式";
		}
		
		initTitle(R.drawable.btn_back_bg, title, 0, 0);

		headicon = (ImageView) findViewById(R.id.imageView1);
		current_qus = (TextView) findViewById(R.id.current_qus);// 当前题号
		question_text = (TextView) findViewById(R.id.question_text);
		radioGroup = (LinearLayout) findViewById(R.id.radiolayout);
		btn_next = (Button) findViewById(R.id.btn_next);
	}

	@Override
	protected void processMainView() {
		
		getTestByModule(module);
	}

	private void getTestByModule(String modoule) {
		Log.e("aa", "modoule is " + modoule);
		TestApi api = new TestApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {

			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(LOAD_PROGRESS);
				if (ApiResult.RESULT_OK == apiResult.getResultCode()) {
					JSONObject jsonEntity = apiResult.getJsonEntity();
					try {
						if (jsonEntity != null) {
							if (jsonEntity.has("status")) {
								String result = jsonEntity.getString("status");
								if (ApiResult.Success.equals(result)) {
									if (jsonEntity.has("data")) {
										JSONArray array = jsonEntity.getJSONArray("data");
										if (array != null && array.length() > 0) {
											if (list == null) {
												list = new ArrayList<Subject>();
											}
											Subject info = null;
											for (int i = 0; i < array.length(); i++) {
												JSONObject obj = (JSONObject) array
														.opt(i);
												info = new Subject();
												info.parser(obj);
												list.add(info);
											}
										}

									}
								}
							}
							updateUI(0);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

			}

			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(LOAD_PROGRESS);

			}

			@Override
			public <T> void onReturnFailResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(LOAD_PROGRESS);
			}
		});
		api.getTesting(1, this, modoule);

	}

	private void updateUI(int position) {
		if (list != null && list.size() > 0&&position<list.size()) {
			Subject subject = list.get(position);
			current_qus.setText((position + 1)+ "/" + list.size());
			question_text.setText(subject.getQuestion());
			if (subject.getAnswers() != null) {
				radioGroup.removeAllViews();
				LinearLayout.LayoutParams groupLP = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
				groupLP.setMargins(Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5));
				RadioGroup group = new RadioGroup(this);
				RadioGroup.LayoutParams radioLP = new RadioGroup.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
				radioLP.setMargins(Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5), Utils.dipToPixels(this, 5));
				for (int i = 0; i < subject.getAnswers().length; i++) {
					String[] answers = subject.getAnswers();
					RadioButton radio = new RadioButton(this);
					radio.setId(i);
					radio.setBackgroundResource(R.drawable.item_creamy_white_bg);
					radio.setTextColor(getResources().getColor(R.color.text_black));
					radio.setButtonDrawable(android.R.color.transparent);
					radio.setGravity(Gravity.CENTER);
					// radio.setText(answers[i].substring(2));
					radio.setText(answers[i]);
					group.addView(radio,radioLP);
				}
				radioGroup.addView(group,groupLP);
			}
		}else {
			btn_next.setText("查看结果");
		}
	}

	@Override
	protected void registerMainViewEvent() {
		btn_next.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_next:
			if (position < list.size()) {
				if (-1 == ((RadioGroup)radioGroup.getChildAt(0)).getCheckedRadioButtonId()) {
					ToastManager.showToast(TesttingActivity.this, "请选择答案!");
					return;
				}
				Log.e("Position", "position is " + position);
				Subject subject = list.get(position);//上传当前回答
				uploadAnswer(getanswer(subject), subject.getCode());
				position++;//更新下一题
				updateUI(position);
			} else {
				Intent intent = new Intent(this, TestResultActivity.class);
				intent.putExtra("module", module);
				startActivity(intent);

			}
			break;
		case R.id.btn_left:
			super.onBackPressed();
			break;
		default:
			break;
		}
	}

	private String getanswer(Subject subject) {
		String[] answers = subject.getAnswers();
		return answers[((RadioGroup)radioGroup.getChildAt(0)).getCheckedRadioButtonId()];
	}

	private void uploadAnswer(String answer, String code) {
		Log.e("upload", "position is " + position + " answer is " + answer);
		if (position < list.size()) {

			TestApi api = new TestApi(this);
			api.setReturnResultListener(new ApiReturnResultListener() {

				@Override
				public <T> void onReturnSucceedResult(int requestCode,
						ApiResult<T> apiResult) {
//					dismissDialog(LOAD_PROGRESS);
					if (ApiResult.RESULT_OK == apiResult.getResultCode()) {
						JSONObject jsonEntity = apiResult.getJsonEntity();
						try {
							if (jsonEntity != null) {
								if (jsonEntity.has("status")) {
									String result = jsonEntity.getString("status");

									if (ApiResult.Success.equals(result)) {
										if(jsonEntity.has("data")) {
											Log.e("Result", "result is " + jsonEntity.getString("data"));
										}
//										ToastManager.showToast(TesttingActivity.this, "添加成功");
									} else {
//										ToastManager.showToast(TesttingActivity.this, "添加失败");
									}
									 
								}
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}

				@Override
				public <T> void onReturnLoading(int requestCode) {
//					showDialog(LOAD_PROGRESS);
				}

				@Override
				public <T> void onReturnFailResult(int requestCode,
						ApiResult<T> apiResult) {
//					dismissDialog(LOAD_PROGRESS);

				}
			});
			api.uploadAnswer(1, this, answer, code);
		}
	}
}
